package com.example.android.wifidirect;

import android.os.Handler;  
import android.os.Message;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class message_sending extends Thread {
	//private WifiDirectService wlib_service = null;
	private String server_address;
	private Handler handler = new Handler();
	private Socket client_socket = null;
	private boolean connected = false;
	private int server_port = 8979;
	private PrintWriter out;
	private String message = "default message";
	
	public void setup( String server_addr, int port) {
		
		server_address = server_addr;
		server_port = port;
	}

	public void setServerAddress(String server_addr) {
		server_address = server_addr;
	}

	public void setMessage(String msg) {
		message = msg;
	}

	public void run() {
		try {
			//if ( server_port == 0 && server_address != null ) return;
			//Socket socket = new Socket();
			client_socket = new Socket(server_address, server_port);
			//client_socket=socket.connect((new InetSocketAddress(server_address, server_port)) , 5000);
			//inform_app("iTrustOutbox: Created client, connecting to " + server_address + ":" + server_port);
			connected = true;
			while ( connected ) {
				//inform_app("Client connected");
				try {
					out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream())), true);
					out.println(message);
					//inform_app("iTrustOutbox: Done sending message.");
				}
				catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		}
		catch (Exception e) {
			//inform_app("iTrustOutbox: Can't connect to peer, because: " + e.toString());
			connected = false;
		}
		//inform_app("iTrustOutbox: Closing outbox client.");
		close_client();
	}

	private void inform_app(String message) {
		final String msg = message;
		handler.post(new Runnable() {
			public void run() {
				//wlib_service.update_outbox_status(msg);
			}
		});
	}

	public void close_client() {
		try {
			client_socket.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}
